//
//  XWCarouselPageView.m
//  CELSP
//
//  Created by wzl on 2016/10/20.
//  Copyright © 2016年 hq88. All rights reserved.
//

#import "XWCarouselPageView.h"
#import "UIImageView+WebCache.h"

@interface XWCarouselPageView()<UIScrollViewDelegate>
/** 轮播的ScrollView */
@property(strong,nonatomic) UIScrollView * direct;
//自定义视图的数组
@property(strong,nonatomic) NSArray *viewArr;
//定时器
@property(strong,nonatomic) NSTimer *timer;
@end
//获取ScrollView的X值偏移量
#define contentOffSet_x self.direct.contentOffset.x
//获取ScrollView的宽度
#define frame_width self.direct.frame.size.width
//获取ScrollView的contentSize宽度
#define contentSize_x self.direct.contentSize.width


@implementation XWCarouselPageView

#pragma mark 静态初始化方法
+(instancetype)directWithFrame:(CGRect)frame
                      ImageArr:(NSArray *)imageNameArray
            AndImageClickBlock:(imageClickBlock)clickBlock{
    
    XWCarouselPageView*carouselPageView = [[XWCarouselPageView alloc] initWithFrame:frame];
    
    [carouselPageView initWithImageArr:imageNameArray AndImageClickBlock:clickBlock];
    
    return carouselPageView;
}

#pragma mark 默认初始化方法
-(void)initWithImageArr:(NSArray *)imageNameArray
           AndImageClickBlock:(imageClickBlock)clickBlock{
    //初始化轮播ScrollView
    self.direct = [[UIScrollView alloc]init];
    self.direct.delegate = self;
    self.direct.pagingEnabled = YES;
    self.direct.frame = self.bounds;
    self.direct.scrollsToTop = NO;
    self.direct.contentOffset=CGPointMake(frame_width, 0);
    self.direct.showsHorizontalScrollIndicator = NO;
    [self addSubview:self.direct];
    
    //初始化轮播页码控件
    self.pageCtrl=[[UIPageControl alloc]init];
    //设置轮播页码的位置
    self.pageCtrl.frame=CGRectMake(0,self.frame.size.height-30, self.frame.size.width, 30);
    _pageCtrl.currentPageIndicatorTintColor = [UIColor colorWithRed:8/255.0 green:169/255.0 blue:204/255.0 alpha:1];
    _pageCtrl.pageIndicatorTintColor = [UIColor grayColor];
    self.carouselPageViewAlignment = XWCarouselPageViewAlignmentCenter;
    [self addSubview:self.pageCtrl];
    
    self.time = 3.0;
    
    //设置滚动图片数组
    self.imageArr=imageNameArray;
    
    //设置图片点击的Block
    self.clickBlock=clickBlock;
}

#pragma mark - 父类方法
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if(self){
        [self initWithImageArr:nil AndImageClickBlock:nil];
    }
    
    return self;
}

#pragma mark - 私有方法
//定时器调用的方法
-(void)timerSel
{
    //获取并且计算当前页码
    CGPoint currentConOffSet=self.direct.contentOffset;
    currentConOffSet.x+=frame_width;
    
    //动画改变当前页码
    [UIView animateWithDuration:0.5 animations:^{
        self.direct.contentOffset=currentConOffSet;
    }completion:^(BOOL finished) {
        [self updataWhenFirstOrLast];
    }];
}

//轮播定时器时间
-(void)setTime:(CGFloat)time
{
    if(time>0)
    {
        _time = time;
        [self stopTimer];
        [self beginTimer];
    }
}

//重写图片名字的数组
-(void)setImageArr:(NSArray *)imageArr
{
    if (_imageArr != imageArr) {
        _imageArr=imageArr;
        //设置ScrollView的contentSize
        NSUInteger count = imageArr.count>0?(imageArr.count+2):1;
        self.direct.contentSize = CGSizeMake(count*frame_width,0);
        
        //设置pageCtrl的个数 位置调整
        if(self.pageCtrl.numberOfPages != imageArr.count){
            self.pageCtrl.numberOfPages = imageArr.count;
            [self updateCarouselPageViewAlignmentStyle];
        }
        
        //添加图片到ScrollView
        [self addImageToScrollView];
        
        //开启定时器
        [self beginTimer];
    }
    
}

//设置小圆点显示样式
-(void)setCarouselPageViewAlignment:(XWCarouselPageViewAlignment)carouselPageViewAlignment{
    if(_carouselPageViewAlignment != carouselPageViewAlignment){
        _carouselPageViewAlignment = carouselPageViewAlignment;
        [self updateCarouselPageViewAlignmentStyle];
    }
}

//图片点击事件
-(void)imageClick:(UITapGestureRecognizer *)tap
{
    if(self.clickBlock)
    {
        self.clickBlock(self.pageCtrl.currentPage);
    }
}

//根据图片名添加图片到ScrollView
-(void)addImageToScrollView
{
    if (self.imageArr.count<=0) {
        return;
    }
    //创建一个可变数组
    NSMutableArray *imgMArr=[NSMutableArray arrayWithArray:self.imageArr];
    //添加第一个和最后一个对象到对应可变数组的最后一个位置和第一个位置
    [imgMArr insertObject:[self.imageArr lastObject] atIndex:0];
    [imgMArr addObject:[self.imageArr firstObject]];
    
    NSInteger tag=-1;
    if (imgMArr.count == 0)
    {
        return;
    }
    for (NSString *name in imgMArr) {
        //将传进来的图片名在本地初始化
        UIImageView *imgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:name]];
        
        //设置图片的坐标
        imgView.frame=CGRectMake(self.frame.size.width*(tag+1), 0, self.frame.size.width, self.frame.size.height);
        
        //如果本地没有这张图片进行网络请求
        if(imgView.image ==nil)
        {
            
            [imgView sd_setImageWithURL:[NSURL URLWithString:name] placeholderImage:nil];
        }

        //添加手势
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageClick:)];
        
        //开启用户交互
        imgView.userInteractionEnabled=YES;
        
        [self.direct addSubview:imgView];
        
        [imgView addGestureRecognizer:tap];
        
        //设置tag
        imgView.tag = tag;
        tag++;
        
    }
    
    self.pageCtrl.numberOfPages = self.imageArr.count;
}

//判断是否第一或者最后一个图片,改变坐标
-(void)updataWhenFirstOrLast
{
    //当图片移动到最后一张时，动画结束移动到第二张图片的位置
    if(contentOffSet_x>=contentSize_x-frame_width)
    {
        self.direct.contentOffset=CGPointMake(frame_width, 0);
    }
    //当图片移动到第一张时，动画结束移动到倒数第二张的位置
    else if (contentOffSet_x<=0)
    {
        self.direct.contentOffset=CGPointMake(contentSize_x-2*frame_width, 0);
    }
    
    //更新PageControl
    NSInteger index=(contentOffSet_x-frame_width)/frame_width;
    self.pageCtrl.currentPage=index;
}

//更新小圆点显示样式
-(void)updateCarouselPageViewAlignmentStyle{
    CGSize pointSize = [self.pageCtrl sizeForNumberOfPages:self.pageCtrl.numberOfPages];
    CGFloat page_y = self.frame.size.height-pointSize.height;
    CGRect page_rect= CGRectMake(0, page_y, pointSize.width+10, pointSize.height);
    
    switch (self.carouselPageViewAlignment) {
        case XWCarouselPageViewAlignmentLeft:
            page_rect.origin.x =  20;
            break;
        case XWCarouselPageViewAlignmentCenter:
            page_rect.origin.x = (self.frame.size.width-page_rect.size.width)/2.0f ;
            break;
        case XWCarouselPageViewAlignmentRight:
           page_rect.origin.x = self.frame.size.width-page_rect.size.width-15;
            break;
            
        default:
            break;
    }
    
    self.pageCtrl.frame = page_rect;
    
}

#pragma mark - 公开方法
//初始化定时器
-(void)beginTimer
{
    [self stopTimer];
    self.timer =[NSTimer scheduledTimerWithTimeInterval:self.time
                                                 target:self
                                               selector:@selector(timerSel) userInfo:nil repeats:YES];
}

//摧毁定时器
-(void)stopTimer
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer=nil;
    }
}

#pragma mark - UIScrollViewDelegate
//开始拖拽代理
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}

//结束拖拽代理
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self beginTimer];
}

//结束滚动代理
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //当最后或者最前一张图片时改变坐标
    [self updataWhenFirstOrLast];
}

@end
